const GITHUB_TOKEN = "5fb2d163c83562dbff5c0a6a9d0891c132f2ca2e";
const GITHUB_REPO = 'cdndb/cto';

module.exports = async (request)=>{
    let url = new URL(request.url)
    let matchs = /\/md\/(\d+)\/(\d{8})\/(.+)\/(.+)$/.exec(url);

    let retJson ;
    if (matchs && matchs.length > 4) {
        let courseId = matchs[1];
        let updateTime = matchs[2];
        let courseUrl = decodeURIComponent(matchs[3]);   
        let cookie = decodeURIComponent(matchs[4]);     

        let jsonObj = {url:courseUrl, updateTime:parseInt(updateTime),cookie:cookie, filetime: new Date().valueOf()};
        console.dir(jsonObj);

        let content = Buffer.from(JSON.stringify(jsonObj), 'utf8').toString('base64');

        let pathname = matchs[1] + '/.url'
        //完整链接
        let uri = "https://api.github.com/repos/" + GITHUB_REPO + "/contents/" + pathname;

        //调整头
        let reqHeaders = {
            "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.33 Safari/537.36",
            "Authorization": "token " + GITHUB_TOKEN,
            "Content-Type": "application/json"
        };

        let getres = await fetch(uri, {
            method: "GET",
            headers: reqHeaders
        })

        let fileSha = null;
        if(getres.status == 200){
            let getrj = await getres.json();
            fileSha = getrj.sha;
            console.log('sha',fileSha);
        }
        else{
            console.log('getres.status', getres.status, getres.statusText);
        }


        //发起 fetch   
        let res = await fetch(uri, {
            method: "PUT",
            body: JSON.stringify({
                message: "update_md",
                sha:fileSha,
                content: content
            }),
            headers: reqHeaders
        });

        //成功
        let outBody, outStatus;
        if ((res.status == 200) || (res.status == 201)) {
            let rj = await res.json();
            outBody = JSON.stringify(rj["content"]);
            outStatus = 200;

            console.log('upload to github:' + pathname);
            retJson = {ok:true, status: res.status}
        } else {
            outBody = await res.text();
            outStatus = res.status;
            console.log('upload to github error:' + outBody);
            retJson = {ok:false, status:res.status}
        }
    }
    else{
        console.log('不符合规范提交');
        retJson = {ok:false,msg:'不符合规范提交'}
    }

    const init = {
        headers: {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "GET, PUT, PATCH, POST, DELETE",
            "Access-Control-Allow-Headers": "*",
            'content-type': 'application/json'
        },
    }
    const body = JSON.stringify(retJson);
    return new Response(body, init);
};